package com.ruoyi.framework.config.security.service;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author cql
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /**
         * 根据用户名查询用户信息，这个用户名是在登录的时候，通过下面这个方法传过来的
         * AuthenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password))
         */
        SysUser user = userService.selectUserByUserName(username);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            /**
             * 抛出自定义异常，全局处理
             */
            throw new RuntimeException("对不起，您的账号：" + username + " 已被删除");
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            /**
             * 抛出自定义异常，全局处理
             */
            throw new RuntimeException("对不起，您的账号：" + username + " 已停用");
        }

        return createLoginUser(user);
    }

    /**
     * 查询用户信息
     *
     * @param user
     * @return
     */
    private UserDetails createLoginUser(SysUser user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setUser(user);
        /**
         * 查询权限信息（菜单和角色）
         */
        loginUser.setPermissions(permissionService.getMenuPermission(user));
        return loginUser;
    }
}
